package org.wattdepot.gdata.kukuicup.updater.energylastsevendays;

import it.sauronsoftware.cron4j.Scheduler;
import it.sauronsoftware.cron4j.Task;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.Updater;

/**
 * The updater that kicks off the Cron4J tasks to run once a day and update the spreadsheets 
 * with the last seven days of daily energy data. 
 * @author Philip Johnson
 *
 */
public class EnergyLastSevenDaysUpdater extends Updater {
  
  /**
   * Creates this updater, initializing the various services. 
   * @param wattDepotService The wattdepot service. 
   * @param gdataService The gdata service.
   * @throws Exception If problems occur initializing these services.  
   */
  public EnergyLastSevenDaysUpdater(WattDepotService wattDepotService, 
      GDataService gdataService) throws Exception {
    super("EnergyLastSevenDays", wattDepotService, gdataService);
  }
  
  /**
   * This task generates a separate TimerTask for each source in the spreadsheet. 
   * Each TimerTask runs every day at one or more minutes past midnight, 
   * gets the daily actual and baseline energy usage for the preceding seven days, and 
   * writes it out to the spreadsheet.
   */
  @Override
  public void run() {
    Scheduler scheduler = new Scheduler();
    schedulers.add(scheduler);
    int startMinute = 1;
    for (String sourceName : sourceNames) {
      Task task = new EnergyLastSevenDaysTask(wattDepotService, gdataService, 
          spreadsheetURL, sourceName, isVirtual(sourceName), getRow(sourceName));
      String schedule = startMinute + " 0 * * *";
      startMinute++;
      System.out.format("Scheduling EnergyLastSevenDays for source: %s at 12:%02d am.%n",
          sourceName, startMinute);
      scheduler.schedule(schedule, task);
    }
    scheduler.start();
  }

}
